package moxl.tokenizer.xml.pibody;

import java.io.IOException;

import moxl.reader.LocateableReader;
import moxl.tokenizer.AbstractTokenizerState;
import moxl.tokenizer.EndOfFileState;
import moxl.tokenizer.Token;
import moxl.tokenizer.TokenReadyState;
import moxl.tokenizer.TokenizerStateMachine;
import moxl.tokenizer.xml.XmlTokenType;

public class ProcessingInstructionBodyStartState extends AbstractTokenizerState
{
	private static ProcessingInstructionBodyStartState instance = new ProcessingInstructionBodyStartState();

	@Override
	public void accept(TokenizerStateMachine stateMachine, Token tok, LocateableReader reader) throws IOException
	{
		reader.mark(2);
		int c = reader.read();
		if (c == -1)
		{
			tok.setTokenType(XmlTokenType.PROCESSING_INSTRUCTION_BODY);
			stateMachine.changeState(EndOfFileState.getInstance());
		}
		else if (c == '?')
		{
			int c2 = reader.read();
			if (c2 == '>')
			{
				tok.setTokenType(XmlTokenType.PROCESSING_INSTRUCTION_BODY);
				stateMachine.changeState(TokenReadyState.getInstance());
				reader.reset();
			}
			else
			{
				tok.append(c);
				tok.append(c2);
			}
		}
		else
		{
			tok.append(c);
		}

	}

	// TODO: These instances should be enumerated.
	public static ProcessingInstructionBodyStartState getInstance()
	{
		return instance;
	}

	@Override
	public boolean isStartState()
	{
		return true;
	}

}
